<?php

namespace app\api\controller;

use app\admin\model\Member;
use app\admin\model\Image;
use app\admin\model\Adbanner;
use app\admin\model\Product;
use app\admin\model\Flashsale;

use think\Db;
use think\Request;

/**
 * 首页
 */
class HomeFrame extends Base
{
    /**
     * 首页数据
     */
    public function getHomeFrame()
    {
        //$param = self::getHttpParam();
        $where = [];

        // 轮播广告
        $adbanners = $this->getAdbanner($where);

        // 限时特价
        // 当前小时
        $nowHour = date('G');
        if ($nowHour >= 7 && $nowHour < 10) {
            $time_range = 7;
        } elseif ($nowHour >= 10 && $nowHour < 13) {
            $time_range = 10;
        } elseif ($nowHour >= 13 && $nowHour < 16) {
            $time_range = 13;
        } elseif ($nowHour >= 16 && $nowHour < 19) {
            $time_range = 16;
        } elseif ($nowHour >= 19 && $nowHour < 21) {
            $time_range = 19;
        } else {
            $time_range = '';
        }
        if ($time_range) {
            // 结束时间的时间戳
            $endTime = strtotime(date('Y-m-d') . ' ' . ($time_range + 2) . ':59:59');
            $flashsaleProducts = $this->getFlashSaleProducts($where, $time_range);
        } else {
            $flashsaleProducts = [];
        }

        // 新品上市
        $newestProducts = $this->getProducts($where, 'create_date DESC');

        // 爆款推荐
        //$recommendProducts = $this->getProducts($where, 'total_sales ASC');
        $recommendProducts = $this->getProductsBySales();

        $data = [
            'adbanners' => $adbanners ? : '',
            'flashsaleProducts' => $flashsaleProducts ? : '',
            'newestProducts' => $newestProducts ? : '',
            'recommendProducts' => $recommendProducts ? : '',
            'endTime' => $endTime
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 获取轮播图
     */
    protected function getAdbanner($where)
    {
        $model = new Adbanner();
        $where['status'] = 1;
        $where['is_del'] = ['eq',0];
        $where['start_time'] = ['elt', date('Y-m-d H:i:s')];
        $where['end_time'] = ['egt', date('Y-m-d H:i:s')];
        $fields = 'id, type, title_url, status_link, link_type, link_detail_product, link_product';

        // 轮播广告
        $carousels = $model->where($where)->where(['type' => 1])->field($fields)->order('create_date DSC')->limit(0, 10)->select();
        $carousels && $carousels = $model->formatDatas($carousels);
        // 大图广告 & 大图广告
        //$pictureAds = $model->where($where)->where(['type' => ['in', '2,3']])->field($fields)->order('create_date DSC')->limit(0, 10)->select();
        $bigAds = $model->where($where)->where(['type' => 2])->field($fields)->order('create_date DSC')->limit(0, 1)->select();
        $bigAds && $bigAds = $model->formatDatas($bigAds);
        $smallAds = $model->where($where)->where(['type' => 3])->field($fields)->order('create_date DSC')->limit(0, 2)->select();
        $smallAds && $smallAds = $model->formatDatas($smallAds);
        // Banner广告
        $banners = $model->where($where)->where(['type' => 5])->field($fields)->order('create_date DSC')->limit(0, 10)->select();
        $banners && $banners = $model->formatDatas($banners);
        // 弹屏广告
        $bombScreen = $model->where($where)->where(['type' => 4])->field($fields)->order('create_date DSC')->find();

        $data = [
            //'carousels' => $this->formatAdbanner($carousels),
            'carousels' => $carousels,
            //'pictureAds' => $pictureAds,
            'bigAds' => $bigAds,
            'smallAds' => $smallAds,
            'banners' => $banners,
            'bombScreen' => $bombScreen
        ];

        return $data;
    }

    // 处理轮播图格式
    /*protected function formatAdbanner($data)
    {
        if ($data) {
            if (is_array($data)) {
                foreach ($data as $item) {
                    $this->formatAdbanner($item);
                }
            } else {
                if ($data['status_detail_product'] == 1) {

                }
            }
        }

        return $data;
    }*/

    /**
     * 获取限时特价商品
     */
    protected function getFlashSaleProducts($where, $time_range = '')
    {
        $where['a.status'] = 1;
        $where['a.start_time'] = ['elt', date('Y-m-d')];
        $where['a.end_time'] = ['egt', date('Y-m-d')];
        if (!$time_range) {
            // 当前小时
            $nowHour = date('G');
            if ($nowHour >= 7 && $nowHour < 10) {
                $time_range = 7;
            } elseif ($nowHour >= 10 && $nowHour < 13) {
                $time_range = 10;
            } elseif ($nowHour >= 13 && $nowHour < 16) {
                $time_range = 13;
            } elseif ($nowHour >= 16 && $nowHour < 19) {
                $time_range = 16;
            } elseif ($nowHour >= 19 && $nowHour < 21) {
                $time_range = 19;
            } else {
                return [];
            }
        }

        $where['a.effective_date'] = ['like', '%,' . $time_range . ',%'];
        $model = new Flashsale();
        $field = 'a.ori_price, a.promotion_type, a.promotion_discount, a.buy_limit_type, a.buy_limit_num, a.start_time, a.end_time, a.effective_date, a.to_user_type, a.to_users, a.range, a.store_ids, b.id, b.name, b.img_url, b.price, b.unit, b.spec, b.describe, b.type';
        $order = 'a.create_date DESC';
        $result = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.product_id = b.id')->field($field)->order($order)->limit(0, 3)->select();
        if (!$result) {
            return [];
        }

        $productMdl = new Product();
        $result = $productMdl->formatProducts($result);

        return $result;
    }

    /**
     * 获取商品
     */
    protected function getProducts($where, $order)
    {
        $where['status'] = 1;
        $where['type'] = 0;
        $where['is_gift'] = 2;

        $model = new Product();
        $field = 'id, name, img_url, price, unit, spec, describe, type';
        //$result = $model->where($where)->field($field)->order($order)->limit(0, 10)->cache(3600)->select(); // 缓存1小时
        $result = $model->where($where)->field($field)->order($order)->limit(0, 10)->select();
        if (!$result) {
            return [];
        }

        $result = $model->formatProducts($result);

        return $result;
    }

    /**
     * 根据销售获取商品
     */
    protected function getProductsBySales()
    {
        //$where['status'] = 1;
        $model = new Product();
        $field = 'id, name, img_url, price, unit, spec, describe, type';
        //$result = $model->where($where)->field($field)->order($order)->limit(0, 10)->select();
        //$sql = "SELECT a.id, a.name, a.img_url, a.price, a.unit, a.spec, a.describe, b.total_sales FROM `store` AS a, (SELECT o.product_id, sum(o.count) as total_sales FROM order_item AS o GROUP BY o.product_id) AS b WHERE a.id = b.product_id AND a.status = 1 ORDER BY b.total_sales DESC LIMIT 0,10";
        $sql = "SELECT a.id, a.name, a.img_url, a.price, a.unit, a.spec, a.describe, a.type, b.total_sales FROM `product` AS a";
        $sql .= ", (SELECT o.product_id, sum(o.count) as total_sales FROM order_item AS o GROUP BY o.product_id) AS b";
        $sql .= " WHERE a.id = b.product_id AND a.status = 1 AND a.type = 0 AND a.is_gift = 2 ORDER BY b.total_sales DESC LIMIT 0,10";

        $result = Db::query($sql);
        if (!$result) {
            return [];
        }

        $result = $model->formatProducts($result);

        return $result;
    }
}